package com.zking.web.LYK;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONObject;
import com.zking.entity.Benefit;
import com.zking.entity.Food;
import com.zking.entity.PageManager;
import com.zking.service.FoodService;
import com.zking.utils.FileOSSUtils;
import com.zking.utils.NumberUtils;
import com.zking.utils.ServletUtils;


@WebServlet("/foodManage")
@MultipartConfig
public class FoodManageServlet extends HttpServlet {


	private static final long serialVersionUID = 1314692864285243590L;
	
	JSONObject jsonObject =new JSONObject();
	FoodService foodService=new FoodService();
	//菜品信息表格路径
	private static String basePath = "food\\Excel\\";
	static {
		//找到电脑上所有的盘符
		//默认存储到最后一个盘
		File[] roots = File.listRoots();
		//拼接最后一个盘符
		basePath = roots[roots.length - 1] + basePath;
		basePath = basePath.replaceAll("\\\\", "/");
		File file = new File(basePath);
		if (file == null || !file.exists()) {
			//创建文件夹
			file.mkdirs();
		}
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String method =request.getParameter("method");
		if(method.equals("showAllFoods")) {
			showAllFoods(request,response);
		}
		else if(method.equals("deleteFood")) {
			try {
				deleteFood(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(method.equals("addFood")) {
			try {
				addFood(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(method.equals("updateFood")) {
			try {
				updateFood(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(method.equals("showImage")) {
			try {
				showImage(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(method.equals("queryFood")) {
			queryFood(request,response);
		}
		else if(method.equals("exportExcel")) {
			try {
				exportExcel(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(method.equals("searchFood")) {
			searchFood(request,response);
		}
		
		else if(method.equals("publishBenefit")) {
			try {
				publishBenefit(request,response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/***
	 * 发布每日特惠
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws SQLException 
	 */
		private void publishBenefit(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
			
			Benefit benefit=ServletUtils.parseParameter(Benefit.class, request);
			//获取当前时间
			Date t = new Date();
			//时间格式话化
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String addTime=df.format(t);
			benefit.setAddTime(addTime);
			//将获取的每日特惠菜品添加到数据库
			foodService.pubishBenefit(benefit);
			
			jsonObject.clear();
			jsonObject.fluentPut("code", 1);
			ServletUtils.send(response, jsonObject);
	}
	/**
	 * 导航栏搜索菜品
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void searchFood(HttpServletRequest request, HttpServletResponse response) throws IOException {
	
		Food food =ServletUtils.parseParameter(Food.class, request);
		int pn =NumberUtils.parseStr(request.getParameter("pn"));
		int limit =NumberUtils.parseStr(request.getParameter("limit"));
		


		List <Food> list=foodService.searchFood(food);
		
		int totalCount = list.size();
		PageManager pm=new PageManager(pn,totalCount,limit);
		
		jsonObject.clear();
		jsonObject.fluentPut("foods", list);
		jsonObject.fluentPut("pm", pm);
		if(totalCount!=0) {
			jsonObject.fluentPut("code", 1);
		}
		else {
			jsonObject.fluentPut("code", -1);
		}
		
		ServletUtils.send(response, jsonObject);
		
	}
	/**
	 * 导出菜品表
	 * @param request
	 * @param response
	 */
	private void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {

		List<Food> foods=foodService.getAllFood();
		
		String filename="foodMsg.xlsx";
		ServletUtils.exportObject(foods,Food.class, basePath,filename);
		File file=new File(basePath+"\\"+filename);
		if(file!=null&&file.exists()) {
			response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("ISO-8859-1")));
			InputStream in =new BufferedInputStream(new FileInputStream(file));
			OutputStream out=new BufferedOutputStream(response.getOutputStream());
			int len=0;
			byte[] b=new byte[1024];
			
			while((len=in.read(b))!=-1) {
				out.write(b,0,len);
			}
			out.flush();
			out.close();
			in.close();
			response.flushBuffer();
		}
		
		
	}
	/**
	 * 查询单个菜品信息
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException 
	 */
	private void queryFood(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Food  food =ServletUtils.parseParameter(Food.class, request);
		
		int pn=Integer.parseInt((request.getParameter("pn")));

		Food food2=foodService.queryFood(food);

		request.setAttribute("food", food2);
		request.setAttribute("pn", pn);
		try {
			try {
				request.getRequestDispatcher("updateFood.jsp").forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 更新菜品信息
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	private void updateFood(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");

		response.setContentType("text/html;charset=utf-8");
	
		
		Food food =ServletUtils.parseParameter(Food.class, request);
		FileOSSUtils fileOssUtils=new FileOSSUtils();
		
		
		Collection<Part> parts =request.getParts();
		jsonObject.clear();
		for (Part part : parts) {
			String fileName=part.getSubmittedFileName();
			if(part.getContentType()!=null&&fileName!=null&&!"".equals(fileName)) {
				fileName=UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
				String filePath ="gc0910/middleProject/group1/food/"+fileName;
				food.setFood_pic(filePath);
				fileOssUtils.uploadFile(part.getInputStream(), filePath);
				
				
			}
		}
		int i=foodService.updateFood(food);
		if(i>0) {
			
			jsonObject.fluentPut("code", 1);
			
		}
		else {
			jsonObject.fluentPut("code", -1);
		}
		ServletUtils.send(response, jsonObject);
	}

	/**
	 * 增加菜品信息
	 * @param request
	 * @param response
	 * @throws ServletException 
	 * @throws IOException 
	 */
	private void addFood(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Food food =ServletUtils.parseParameter(Food.class, request);
		FileOSSUtils fileOssUtils=new FileOSSUtils();
		Collection<Part> parts =request.getParts();
		jsonObject.clear();
		for (Part part : parts) {
			String fileName=part.getSubmittedFileName();
			if(part.getContentType()!=null&&fileName!=null&&!"".equals(fileName)) {
				fileName=UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
				String filePath ="gc0910/middleProject/group1/food/"+fileName;
				food.setFood_pic(filePath);
				fileOssUtils.uploadFile(part.getInputStream(), filePath);
				
				
			}
		}
		int i=foodService.addFood(food);
		
		if(i>0) {
		
			jsonObject.fluentPut("code", 1);
			
		}
		else {
			jsonObject.fluentPut("code", -1);
		}
		ServletUtils.send(response, jsonObject);
		
	}

	/**
	 * 删除菜品信息
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	private void deleteFood(HttpServletRequest request, HttpServletResponse response) throws Exception {
				Food food =ServletUtils.parseParameter(Food.class, request);
				int i=foodService.deleteFood(food);
			
				jsonObject.clear();
				if(i>0) {
					jsonObject.fluentPut("code", 1);
				
					
				}
				else {
					jsonObject.fluentPut("code", -1);
				}
				ServletUtils.send(response, jsonObject);
		
	}

	/**
	 * 显示所有菜品信息
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void showAllFoods(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int pn =NumberUtils.parseStr(request.getParameter("pn"));
		int limit =NumberUtils.parseStr(request.getParameter("limit"));
		
		int totalCount = foodService.getTotalCount();
		PageManager pm=new PageManager(pn,totalCount,limit);
		List<Food> foods =foodService.queryFoods(pm);
		jsonObject.clear();
		jsonObject.fluentPut("foods", foods);
		jsonObject.fluentPut("pm", pm);
		ServletUtils.send(response, jsonObject);
		
		
	}

	/**
	 * 显示图片
	 * @param request
	 * @param response
	 */
	private void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception{
		FileOSSUtils fileOssUtils=new FileOSSUtils();
		String path =request.getParameter("path");
		BufferedInputStream in=new BufferedInputStream(fileOssUtils.getInStream(path));
		BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
		int len=0;
		byte[] b=new byte[1024];
		while((len=in.read(b))!=-1) {
			out.write(b,0,len);
		}
		out.flush();
		out.close();
		in.close();
		//刷新一下响应的缓存
		response.flushBuffer();
	}


	
}
